我正在使用webpack并尝试利用用TS编写的现有React组件库。
但是,通过以下设置,webpack会出现“意外令牌”错误。我将有问题的代码复制到babel online transpiler https://babeljs.io/repl/,但它没有显示任何错误。
我对React开发很新,欢迎任何批评/问题/答案。
谢谢!
这是我的 webpack.config.js
var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
context: __dirname,
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/static/js/index'
],
output: {
path: path.resolve('./app/static/bundles/'),
filename: '[name]-[hash].js',
publicPath: 'http://localhost:3000/static/bundles/',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new BundleTracker({filename: './webpack-stats.json'}),
],
module: {
loaders: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: ["babel-loader?presets[]=es2015,presets[]=react"],
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
configFileName: './tsconfig.json'
},
exclude: /node_modules/
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.css']
}
}
我的入口点文件 index.js :
import React from 'react';
import ReactDOM from 'react-dom';
import * as PropTypes from 'prop-types';
interface IDemoState {
value ?: string;
}
class Test extends React.Component<{}, IDemoState> {
state: IDemoState = {
value : 'general'
}
}
ReactDOM.render(<Test />, document.getElementById('tabnav'));
的package.json
{
"name": "djangoproject",
"version": "1.0.0",
"description": "Django Project",
"main": "index.js",
"scripts": {
"build": "webpack --config webpack.config.js --progress --colors",
"build-production": "webpack --config webpack.prod.config.js --progress --colors",
"watch": "node server.js"
},
"keywords": [
"Django"
],
"license": "ISC",
"devDependencies": {
"adp-css-framework": "^1.5.3",
"adp-react-components": "^1.4.3",
"adp-react-icons": "^1.16.0",
"babel": "^6.23.0",
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-loader": "^7.1.0",
"babel-preset-env": "^1.5.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.4",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-hot-loader": "^1.3.1",
"style-loader": "^0.18.2",
"ts-loader": "^2.2.1",
"typescript": "^2.4.1",
"webpack": "^3.0.0",
"webpack-bundle-tracker": "^0.2.0",
"webpack-dev-server": "^2.5.0"
}
}
如果我运行 npm run watch ,我收到此错误:
ERROR in ./app/static/js/index.js
Module build failed: SyntaxError: xxxxx./app/static/js/index.js: Unexpected token (10:20)
8 |
9 | class Test extends React.Component<{}, IDemoState> {
> 10 | state: IDemoState = {
| ^
11 | value : 'general'
12 | }
13 | }
@ multi webpack-dev-server/client?http://localhost:3000 webpack/hot/only-dev-se
rver ./app/static/js/index
答案 0 :(得分:1)
在将ts-loader更改为awesome-typescript-loader并将所有内容写入tsx文件后,问题终于消失了。